package so.ruo.api;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.log4j.Logger;
import org.jsoup.helper.StringUtil;

import com.attilax.shbye.YejmX;

public class Api {

	private Logger logger = Logger.getLogger(Api.class);
	private String msg = null;
	private HttpClientContext context = null;
	private CloseableHttpClient httpclient = null;
	private CloseableHttpResponse response = null;
	private HttpHost targetHost = null;
	private HttpHost proxyHost = null;
	private CookieStore cookieStore = null;
	private Proxy proxy = null;
	private Header[] headers = null;
	private RequestConfig config = null;
	private Map<String, String> headMap = null;
	private String charset = "utf-8";
	private long contentLength = -1;
	private String returns = null;
	private LaxRedirectStrategy redirectStrategy = null;
	private String httpType = "POST";
	private List<Cookie> cookies = null;

	/**
	 * 对外开放API
	 * 
	 * @throws Exception
	 */
	public boolean comment(String username, String password, SiteType siteType, String comment, String url, Proxy proxy) throws Exception {
		
		// 代理IP查询链接 http://www.kuaidaili.com/

		BaseAuth auth = null;
		BaseComment baseComment = null;

		if (StringUtil.isBlank(username)) {
			throw new Exception("用户账号为空");
		}

		if (StringUtil.isBlank(password)) {
			throw new Exception("用户密码为空");
		}

		if (siteType == null) {
			throw new Exception("网站类型为空");
		}

		if (StringUtil.isBlank(comment)) {
			throw new Exception("评论为空");
		}

		if (StringUtil.isBlank(url)) {
			throw new Exception("链接为空");
		}

		Map<String, String> headMap = new HashMap<String, String>();
		// 请求Header
		headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
		headMap.put("Content-Type", "text/html;charset=UTF-8");
		headMap.put("Accept-Language", "zh-cn");
		headMap.put("Accept-Encoding", "gzip, deflate");
		headMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		headMap.put("Connection", "keep-alive");
		headMap.put("DNT", "1");
		headMap.put("Cache-Control", "no-cache");
		headMap.put("Pragma", "no-cache");
		headMap.put("X-Requested-With", "XMLHttpRequest");

		if (SiteType.IFENG == siteType) {// 凤凰
			try {
				auth = new BaseAuth();
				auth.setProxy(proxy);
				String host = "jifen.ifeng.com/";
				String site = "http://jifen.ifeng.com/index/login/?username=" + username + "&password=" + password + "&inpass=on";
				Map<String, String> postInfo = new HashMap<String, String>();
				postInfo.put("username", username);
				postInfo.put("password", password);
				postInfo.put("inpass", "on");

				String authreturns = auth.login(host, site, postInfo);
				if (authreturns.contains("class=\"userid\" title=\"凤凰网帐号：")) {
					logger.info("[" + username + "]凤凰账号登录成功");
				} else {
					msg = "登录失败\n" + authreturns;
					return false;
				}
				logger.info("登录返回信息:" + authreturns);

				// 获取docName
				Thread.sleep(1000);
				httpclient = auth.getHttpclient();
				context = auth.getContext();
				targetHost = auth.getTargetHost();
				proxyHost = auth.getProxyHost();
				host = "news.ifeng.com";
				if (proxy != null) {
					targetHost = new HttpHost(host, 443, "http"); // 设定目标站点
				}

				HttpTools tool = new HttpTools();
				tool.setContext(context);
				tool.setHttpclient(httpclient);
				tool.setProxy(proxy);
				tool.setTargetHost(targetHost);
				tool.setProxyHost(proxyHost);
				String content = tool.getRequest(url);

				// 打印cookies
				// Tools.printCookies(auth.getContext().getCookieStore().getCookies());

				// 获取sid
				String sid = "";
				cookies = auth.getContext().getCookieStore().getCookies();

				String docName = "";
				String docUrl = "";
				String skey = "";
				content = content.replaceAll("[\\t\\n\\r]", "");// 将内容区域的回车换行去除
				String regx1 = "\"docName\"(.*?):(.*?)\"(.*?)\"(.*?)\"docUrl\"(.*?):(.*?)\"(.*?)\"(.*?)\"skey\"(.*?):(.*?)\"(.*?)\"(.*?)";//
				Pattern p = Pattern.compile(regx1);
				String text = content.toString();
				Matcher macher = p.matcher(text);
				boolean isMacher = macher.find();
				if (isMacher) {
					docName = macher.group(3).trim();
					docUrl = macher.group(7).trim();
					skey = macher.group(11).trim();
				}
				// content=%E5%A5%BD%E6%83%B3%E5%8E%BB%E5%91%80....&docName=%E9%93%B6%E5%B7%9D+%E6%B2%99%E6%BC%A0%E6%8E%A2%E9%99%A9%E5%AF%93%E6%95%99%E4%BA%8E%E4%B9%90%E4%B8%A4%E4%B8%8D%E8%AF%AF&docUrl=http%3A%2F%2Fnews.ifeng.com%2Fa%2F20150520%2F43799514_0.shtml&speUrl=&skey=e0cbfe
				host = "comment.ifeng.com";
				site = "http://comment.ifeng.com/post/?format=json&sid=" + sid;
				site = site + "&docUrl=" + URLEncoder.encode(docUrl, "utf-8") + "&docName=" + URLEncoder.encode(docName, "utf-8");
				site = site + "&skey=" + skey + "&content=" + URLEncoder.encode(comment, "utf-8") + "&speUrl=";
				baseComment = new BaseComment();
				postInfo = new HashMap<String, String>();

				postInfo.put("docUrl", URLEncoder.encode(docUrl, "utf-8"));
				postInfo.put("docName", URLEncoder.encode(docName, "utf-8"));
				postInfo.put("speUrl", "");
				postInfo.put("skey", skey);
				postInfo.put("sid", sid);
				postInfo.put("content", comment);

				baseComment.setHttpclient(httpclient);
				baseComment.setContext(context);
				baseComment.setProxy(proxy);
				// Head
				String referer = "http://comment.ifeng.com/view.php?docUrl=" + URLEncoder.encode(docUrl, "utf-8") + "&docName=" + URLEncoder.encode(docName, "utf-8") + "&skey=" + skey;
				headMap.put("Referer", referer);
				headMap.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				headMap.put("X-Requested-With", "XMLHttpRequest");
				headMap.put("Accept-Language", "zh-cn");
				headMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
				headMap.put("Origin", "http://comment.ifeng.com");
				baseComment.setHeadMap(headMap);

				content = baseComment.post(host, site, postInfo);
				logger.info(content);
				// 不管有没有提交成功登出账号
				String logoutContent = tool.getRequest("http://my.ifeng.com/logout");
				System.out.println(logoutContent);
				if (content.contains("\"code\":1")) {
					logger.info("[" + comment + "]凤凰跟帖提交成功");
					return true;
				} else {
					msg = "提交跟帖失败\n" + content;
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("提交凤凰跟帖出错了", e);
				msg = "未知错误,请查看日志";
				return false;
			} finally {
				httpclient.close();
			}
		} else if (SiteType.SINA == siteType) {// 新浪

			return process_sina(username, password, comment, url, proxy, headMap);
				// 打印cookies
				// Tools.printCookies(sinaAuth.getContext().getCookieStore().getCookies());

				// 获取docName


				
				
				
				




				// Head


				// 不管有没有提交成功登出账号



		} else if (SiteType.SOHU == siteType) {// 搜狐
			try {
				// 登录
				auth = new BaseAuth();
				String host = "passport.sohu.com";
				// String site = "http://passport.sohu.com/sso/login.jsp";
				String site = "http://plus.sohu.com/a/spassport/plogin?cb=jQuery19105705085983499885_" + new Date().getTime();
				Map<String, String> postInfo = new HashMap<String, String>();
				postInfo.put("loginName", username);
				postInfo.put("pwd_md5", DigestUtils.md5Hex(password));
				postInfo.put("_input_encode", "utf-8");
				postInfo.put("rememberMe", "1");
				postInfo.put("_", "" + new Date().getTime());
				logger.info(DigestUtils.md5Hex(password));
				auth.setProxy(proxy);
				String authreturns = auth.login(host, site, postInfo);
				if (authreturns.contains("login success")) {
					logger.info("[" + username + "]搜狐账号登录成功");
				} else {
					msg = "登录失败\n" + authreturns;
					return false;
				}
				logger.info("登录返回信息:" + authreturns);

				// 打印Cookie
				// List<Cookie> cookies = auth.getContext().getCookieStore().getCookies();
				// Tools.printCookies(cookies);

				httpclient = auth.getHttpclient();
				context = auth.getContext();
				targetHost = auth.getTargetHost();
				proxyHost = auth.getProxyHost();

				HttpTools tool = new HttpTools();
				tool.setContext(context);
				tool.setHttpclient(httpclient);
				tool.setProxy(proxy);
				tool.setTargetHost(targetHost);
				tool.setProxyHost(proxyHost);

				String content = tool.getRequest(url);

				String topicsid = "";
				String regx1 = "\\/n(.*?).shtml(.*?)";
				Pattern p = Pattern.compile(regx1);
				String text = url.toString();
				Matcher macher = p.matcher(text.replace("news.sohu.com", ""));
				boolean isMacher = macher.find();
				if (isMacher) {
					topicsid = macher.group(1).trim();
				}

				content = tool
						.getRequest("http://changyan.sohu.com/node/html?t=" + new Date().getTime() + "&callback=fn&appid=cyqemw6s1&conf=prod_0266e33d3f546cb5436a10798e657d97&confstr=prod_0266e33d3f546cb5436a10798e657d97&client_id=cyqemw6s1&topicurl=http%253A%252F%252Fquan.sohu.com%252Fpinglun%252Fcyqemw6s1%252F417128916&topicsid=" + topicsid + "&spSize=5&pageConf=%7B%7D");

				String topicId = "";
				content = content.replaceAll("[\\t\\n\\r]", "");// 将内容区域的回车换行去除
				logger.info("____" + content);
				regx1 = ",\"topic_id\":(.*?),";//
				p = Pattern.compile(regx1);
				text = content.toString();
				macher = p.matcher(text);
				isMacher = macher.find();
				if (isMacher) {
					topicId = macher.group(1).trim();
				}
				if (topicId.contains("}")) {
					topicId = topicId.replace("}", "");
				}
				logger.info("topicId=" + topicId);
				// 打印Cookie
				CookieStore cookieStore = auth.getContext().getCookieStore();
				cookies = cookieStore.getCookies();

				// Tools.printCookies(cookies);

				host = "changyan.sohu.com";
				site = "http://changyan.sohu.com/api/2/comment/submit?client_id=cyqemw6s1&topic_id=" + topicId + "&content=" + comment + "&cmt_bold=false&cmt_color=false&dataType=&cmtNum=&floorNum=&attachment_urls=";

				baseComment = new BaseComment();
				postInfo = new HashMap<String, String>();
				postInfo.put("topic_id", topicId);
				postInfo.put("content", comment);
				postInfo.put("floorNum", "");
				postInfo.put("dataType", "");
				postInfo.put("cmtNum", "");
				postInfo.put("cmt_color", "false");
				postInfo.put("cmt_bold", "false");
				postInfo.put("client_id", "cyqemw6s1");
				postInfo.put("attachment_urls", "");

				baseComment.setHttpclient(httpclient);
				baseComment.setContext(context);
				baseComment.setProxy(proxy);
				// Head
				headMap.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				headMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
				headMap.put("Referer", "http://quan.sohu.com/pinglun/cyqemw6s1/" + topicsid);
				baseComment.setHeadMap(headMap);
				// for (int i = 0; i < 10; i++) {
				content = tool.getRequest(site);
				logger.info(content);
				// }
				// 不管有没有提交成功登出账号
				String logoutContent = tool.getRequest("http://passport.sohu.com/sso/logout.jsp?s=" + new Date().getTime() + "&appid=9999");
				logger.info(logoutContent);
				if (content.contains("{\"id\":")) {
					logger.info("[" + comment + "]搜狐跟帖提交成功");
					return true;
				} else {
					msg = "提交跟帖失败\n" + content;
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("提交搜狐跟帖出错了", e);
				msg = "未知错误,请查看日志";
				return false;
			} finally {
				httpclient.close();
			}

		} else if (SiteType.TENCENT == siteType) {// 腾讯

		} else if (SiteType.WANGYI == siteType) {// 网易
			try {
				// 登录
				auth = new BaseAuth();
				auth.setProxy(proxy);// 设置代理服务器
				String host = "reg.163.com";
				String site = "https://reg.163.com/logins.jsp";// 提交登录链接

				Map<String, String> postInfo = new HashMap<String, String>();
				postInfo.put("username", username);
				postInfo.put("password", password);
				postInfo.put("type", "1");
				postInfo.put("product", "urs");
				// postInfo.put("noRedirect", "1");
				postInfo.put("url", "");
				// postInfo.put("ticket", "");
				postInfo.put("url2", "http://reg.163.com/UserLogin.do");

				String authreturns = auth.login(host, site, postInfo);

				httpclient = auth.getHttpclient();
				context = auth.getContext();
				targetHost = auth.getTargetHost();
				proxyHost = auth.getProxyHost();

				HttpTools tool = new HttpTools();
				tool.setContext(context);
				tool.setHttpclient(httpclient);
				tool.setProxy(proxy);
				tool.setTargetHost(targetHost);
				tool.setProxyHost(proxyHost);
				String content = tool.getRequest(url);

				if (authreturns.contains("正在登录，请稍等...")) {
					logger.info("[" + username + "]网易账号登录成功");
				} else {
					// msg="登录失败\n"+authreturns;
					return false;
				}
				// logger.info("登录返回信息:" + authreturns);

				// 打印cookies
				// Tools.printCookies(auth.getContext().getCookieStore().getCookies());

				// 获取boardId
				String boardId = "news_guonei8_bbs";
				content = content.replaceAll("[\\t\\n\\r]", "");// 将内容区域的回车换行去除
				String regx1 = "boardId(.*?)=(.*?)\"(.*?)\"(.*?)";//
				Pattern p = Pattern.compile(regx1);
				String text = content.toString();
				Matcher macher = p.matcher(text);
				boolean isMacher = macher.find();
				if (isMacher) {
					boardId = macher.group(3).trim();
				}

				logger.info("=============" + boardId);

				content = tool.getRequest("http://comment.news.163.com/reply/needvalidate.jsp?time=" + new Date().getTime());

				// 发表评论
				host = "comment.news.163.com";
				site = "http://comment.news.163.com/reply/dopost.jsp";

				String[] temp = url.split("\\/");
				String threadid = temp[temp.length - 1].replace(".html", "");

				site = site + "?body=" + URLEncoder.encode(comment, "utf-8") + "&board=" + boardId + "&username=&threadid=" + threadid + "&url=" + URLEncoder.encode(url, "utf-8") + "&isTinyBlogSyn=-1";

				baseComment = new BaseComment();
				postInfo = new HashMap<String, String>();
				postInfo.put("username", "");
				postInfo.put("body", comment);
				postInfo.put("board", boardId);
				postInfo.put("threadid", threadid);
				postInfo.put("isTinyBlogSyn", "-1");
				postInfo.put("flag", "");
				postInfo.put("quote", "");
				postInfo.put("url", url);
				postInfo.put("hidename", "false");
				postInfo.put("validateCode", "0");

				baseComment.setHttpclient(httpclient);
				baseComment.setContext(context);
				baseComment.setProxy(proxy);
				baseComment.setTargetHost(targetHost);
				baseComment.setProxyHost(proxyHost);
				// Head
				headMap.put("Referer", "http://comment.news.163.com/news_guonei8_bbs/" + threadid + ".html");
				baseComment.setHeadMap(headMap);

				content = baseComment.post(host, site, postInfo);
				// logger.info(content);
				// 不管有没有提交成功登出账号
				String logoutContent = tool.getRequest("http://reg.163.com/Logout.jsp");
				logger.info(logoutContent);
				if (content.contains("网友跟贴")) {
					logger.info("[" + comment + "]网易跟帖提交成功");
					return true;
				} else {
					msg = "提交跟帖失败\n" + content;
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("提交网易跟帖出错了", e);
				msg = "未知错误,请查看日志";
				return false;
			} finally {
				httpclient.close();
			}
		} else {
			throw new Exception("网站类型不匹配");
		}
		return false;
	}

	private boolean process_sina(String username, String password, String comment, String url, Proxy proxy, Map<String, String> headMap) throws IOException {
		BaseComment baseComment;
		try {
			SinaAuth sinaAuth = new SinaAuth();
			sinaAuth.setProxy(proxy);
			String host = "i.sso.sina.com.cn";
			String site = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=" + new Date().getTime();
			Map<String, String> postInfo = new HashMap<String, String>();
			postInfo.put("mobile", username);
			postInfo.put("password", password);
			String authreturns = sinaAuth.login(host, site, postInfo);
			if (authreturns.contains("\"result\":true")) {
				logger.info("[" + username + "]新浪账号登录成功");
			} else {
				msg = "登录失败\n" + authreturns;
				System.out.println(msg);
				return false;
			}
			logger.info("登录返回信息:" + authreturns);
			httpclient = sinaAuth.getHttpclient();
			context = sinaAuth.getContext();
			targetHost = sinaAuth.getTargetHost();
			proxyHost = sinaAuth.getProxyHost();
			HttpTools tool = new HttpTools();
			tool.setContext(context);
			tool.setHttpclient(httpclient);
			tool.setProxy(proxy);
			tool.setTargetHost(targetHost);
			tool.setProxyHost(proxyHost);
			String content = tool.getRequest(url);
			String newsid = "";
			content = content.replaceAll("[\\t\\n\\r]", "");// 将内容区域的回车换行去除
			String regx1 = "newsid(.*?):(.*?)\'(.*?)\'(.*?)";//
			Pattern p = Pattern.compile(regx1);
			String text = content.toString();
			Matcher macher = p.matcher(text);
			boolean isMacher = macher.find();
			if (isMacher) {
				newsid = macher.group(3).trim();
			}
			String channel = "";
			content = tool.getRequest(url);
			content = content.replaceAll("[\\s\\t\\n\\r]", "");// 将内容区域的回车换行去除
			logger.info("content"+content);
			String regx2 = "channel:\'(.*?)\'(.*?)";//
			Pattern  p2 = Pattern.compile(regx2);
			String text2 = content.toString();
			 Matcher macher2 = p2.matcher(text2);
			 boolean isMacher2 = macher2.find();
			if (isMacher2) {
				channel = macher2.group(1).trim();
			}
			logger.info(channel+"=============" + newsid);
			host = "news.sina.com.cn";
			site = "http://comment5.news.sina.com.cn/cmnt/submit";
			baseComment = new BaseComment();
			postInfo = new HashMap<String, String>();
			postInfo.put("encoding", "gbk");
			postInfo.put("channel", channel);
			postInfo.put("newsid", newsid);
			postInfo.put("parent", "");
			postInfo.put("content", comment);
			postInfo.put("format", "json");
			postInfo.put("ie", "gbk");
			postInfo.put("oe", "gbk");
			postInfo.put("ispost", "");
			postInfo.put("share_url", URLEncoder.encode(url, "utf-8"));
			postInfo.put("video_url", "");
			postInfo.put("img_url", "");
			postInfo.put("iframe", "1");
			postInfo.put("callback", "iJax" + new Date().getTime());
			baseComment.setHttpclient(httpclient);
			baseComment.setContext(context);
			baseComment.setProxy(proxy);
			baseComment.setCharset("gb2312");
			headMap.put("Referer", url);
			headMap.put("Content-Type", "text/html;charset=gbk");
			baseComment.setHeadMap(headMap);
			content = baseComment.post(host, site, postInfo);
			String logoutContent = tool.getRequest("http://login.sina.com.cn/sso/logout.php?entry=account&callback=pluginSSOController.ssoLogoutCallBack&sr=1920*1080&client=ssologin.js(v1.4.18)&_=" + new Date().getTime());
			logger.info(logoutContent);
			logger.info(content);
			if (content.contains("\"code\": 0")) {
				logger.info("[" + comment + "]新浪跟帖提交成功");
				return true;
			} else {
				msg = "提交跟帖失败\n" + content;
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("提交新浪跟帖出错了", e);
			msg = "未知错误,请查看日志";
			return false;
		} finally {
			httpclient.close();
		}
	}
	public Logger getLogger() {
		return logger;
	}

	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

}
